package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ProjectProgressOriginal.ProjectProgressSuper;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class DetailProjectProgressFragment extends Fragment {

  public static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.DetailProjectProgressFragment.EXTRA_CONTENT";
  public static final String EXTRA_PROJECT_ID =
      "com.isunland.managesystem.ui.DetailProjectProgressFragment.EXTRA_PROJECT_ID";
  public static final String EXTRA_PROJECT_NAME =
      "com.isunland.managesystem.ui.DetailProjectProgressFragment.EXTRA_PROJECT_NAME";
  public static final String EXTRA_PM_ID =
      "com.isunland.managesystem.ui.DetailProjectProgressFragment.EXTRA_PM_ID";

  public static final String EXTRA_TYPE =
      "com.isunland.managesystem.ui.DetailProjectProgressFragment.EXTRA_TYPE";

  private static final int CHECKED = 0;
  private static final int CHECKED_DATE = 1;
  private static final int PROGRESS_REGIST = 2;

  private TextView mEtprojectState;
  private TextView mTvprojectStartTime;
  private TextView mTvprojectEndTime;
  private TextView mTvprojectplanStartTime;
  private TextView mTvprojectPlanEndTime;
  private TextView mTvprojectDelayTime;
  private TextView mTvprojectKeepTime;
  private TextView mTvprojectEndFlag;
  private TextView mTvdelayCause;
  private TextView mTvprojectMilestone;
  private TextView mTvstatePrinciple;
  private TextView mTvprojectRemark;
  private TextView mTvcheckor;
  private TextView mTvprojectCheckTime;
  //	    private TextView mTvprojectStateStatus;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private ProjectProgressSuper superContent;
  private String type = "";
  private String pmId = "";
  private String projectId = "";
  private String projectName = "";
  private String backType = "";

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    superContent = (ProjectProgressSuper) getArguments().getSerializable(EXTRA_CONTENT);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    pmId = (String) getArguments().getSerializable(EXTRA_PM_ID);
    projectId = (String) getArguments().getSerializable(EXTRA_PROJECT_ID);
    projectName = (String) getArguments().getSerializable(EXTRA_PROJECT_NAME);
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_project_progress, menu);
    menu.getItem(0).setVisible(false).setEnabled(false);
    menu.getItem(1).setVisible(false).setEnabled(false);
    menu.getItem(2).setVisible(false).setEnabled(false);
    menu.getItem(3).setVisible(false).setEnabled(false);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      //进展登记
      case R.id.menu_item_regist:

        if ("publish".equals(superContent.getRealDataStatus())) {
          ToastUtil.show(R.string.no_regist);
        } else {
          if ((mUser.getJobNumber()).equals(superContent.getChargeManId()) || (mUser.getJobNumber())
              .equals(pmId)) {
            Intent i = new Intent(getActivity(), RegistProjectProgressActivity.class);
            i.putExtra(RegistProjectProgressFragment.EXTRA_CONTENT, superContent);
            i.putExtra(RegistProjectProgressFragment.EXTRA_PROJECT_NAME, projectName);
            startActivityForResult(i, PROGRESS_REGIST);
          } else {
            ToastUtil.show(R.string.pm_regist);
          }
        }

        break;
      //提交
      case R.id.menu_item_submit:

        if ((mUser.getJobNumber()).equals(superContent.getChargeManId())
            || (mUser.getJobNumber()).equals(pmId)) {

          if ("new".equals(superContent.getRealDataStatus()) || "newback".equals(
              superContent.getRealDataStatus())) {
            type = "submit";
            volleyPost(type);
          } else {

            ToastUtil.show(R.string.submit_toast);
          }
        } else {

          ToastUtil.show(R.string.pass_pm_toast);
        }

        break;
      //审核通过
      case R.id.menu_item_pass:

        if ("submit".equals(superContent.getRealDataStatus()) || "newback".equals(
            superContent.getRealDataStatus())) {

          if ((mUser.getJobNumber()).equals(superContent.getChargeManId()) || (mUser.getJobNumber())
              .equals(pmId)) {
            type = "publish";
            volleyPost(type);
          } else {
            ToastUtil.show(R.string.pass_pm_toast);
          }
        } else {
          ToastUtil.show(R.string.pass_toast);
        }

        break;
      //退回修改
      case R.id.menu_item_back:
        if (!(mUser.getJobNumber()).equals(superContent.getRealCheckStaffId())) {
          ToastUtil.show(R.string.newback_checkstaff_toast);
        } else {
          if ("submit".equals(superContent.getRealDataStatus()) || "publish".equals(
              superContent.getRealDataStatus())) {
            type = "newback";
            volleyPost(type);
          } else {
            ToastUtil.show(R.string.newback_status_toast);
          }
        }

        break;
      //项目验收
      case R.id.menu_item_checked:
        if (pmId.equals(mUser.getJobNumber())) {
          showDialog(CHECKED);
        } else {
          ToastUtil.show(R.string.pm_checked);
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case CHECKED:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.cheecked_remaind,
            R.string.restart_title);

        break;
      case CHECKED_DATE:
        dialog = new BaseYMDTimeDialogFragment();

        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(DetailProjectProgressFragment.this, requestCode);
    dialog.show(fm, "");
  }

  private void volleyPost(String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_CHANGR_STATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", superContent.getId());
    params.put("realDataStatus", type);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response(type));
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_project_detail, container, false);
    initData(v);
    return v;
  }

  private void initData(View v) {

    mEtprojectState = (TextView) v.findViewById(R.id.et__projectState);
    mTvprojectStartTime = (TextView) v.findViewById(R.id.tv_projectStartTime);
    mTvprojectEndTime = (TextView) v.findViewById(R.id.tv_projectEndTime);
    mTvprojectplanStartTime = (TextView) v.findViewById(R.id.tv_projectplanStartTime);
    mTvprojectPlanEndTime = (TextView) v.findViewById(R.id.tv_projectPlanEndTime);
    mTvprojectDelayTime = (TextView) v.findViewById(R.id.tv_projectDelayTime);
    mTvprojectKeepTime = (TextView) v.findViewById(R.id.tv_projectKeepTime);
    mTvprojectEndFlag = (TextView) v.findViewById(R.id.tv_projectEndFlag);
    mTvdelayCause = (TextView) v.findViewById(R.id.tv_delayCause);
    mTvprojectMilestone = (TextView) v.findViewById(R.id.tv_projectMilestone);
    mTvstatePrinciple = (TextView) v.findViewById(R.id.tv_statePrinciple);
    mTvprojectRemark = (TextView) v.findViewById(R.id.tv_projectRemark);
    mTvcheckor = (TextView) v.findViewById(R.id.tv_checkor);
    mTvprojectCheckTime = (TextView) v.findViewById(R.id.tv_projectCheckTime);
    //        mTvprojectStateStatus = (TextView) v.findViewById(R.id.tv_projectStateStatus);

    mEtprojectState.setText(superContent.getStageName());
    mTvprojectStartTime.setText(superContent.getActSTime());
    mTvprojectEndTime.setText(superContent.getActETime());
    mTvprojectplanStartTime.setText(superContent.getPlanSTime());
    mTvprojectPlanEndTime.setText(superContent.getPlanETime());
    mTvprojectDelayTime.setText(superContent.getPostDays());
    mTvprojectKeepTime.setText(superContent.getActAllDaynum());
    mTvprojectEndFlag.setText(superContent.getEndFlagDesc());
    mTvdelayCause.setText(superContent.getDelayReason());
    if (!TextUtils.isEmpty(superContent.getIfMilepost())) {
      if ("F".equals(superContent.getIfMilepost())) {
        mTvprojectMilestone.setText("否");
      } else if ("T".equals(superContent.getIfMilepost())) {
        mTvprojectMilestone.setText("是");
      }
    } else {
      mTvprojectMilestone.setText("");
    }

    mTvstatePrinciple.setText(superContent.getChargeManName());
    mTvprojectRemark.setText(superContent.getRemark());
    mTvcheckor.setText(superContent.getRealCheckStaffName());
    mTvprojectCheckTime.setText(superContent.getRealCheckDate());
    //	  new 草稿 submit 已提交 publish 已发布 newback 退回修改
    //	  if ("new".equals(superContent.getRealDataStatus())) {
    //		  mTvprojectStateStatus.setText(R.string.draft);
    //	}
    //	  else if ("submit".equals(superContent.getRealDataStatus())) {
    //		  mTvprojectStateStatus.setText(R.string.already_submit);
    //	  }
    //	  else if ("publish".equals(superContent.getRealDataStatus())) {
    //		  mTvprojectStateStatus.setText(R.string.hasAudited);
    //	  }
    //	  else if ("newback".equals(superContent.getRealDataStatus())) {
    //		  mTvprojectStateStatus.setText(R.string.removeCheck);
    //	  }

  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHECKED) {

      showDialog(CHECKED_DATE);
    }

    if (requestCode == CHECKED_DATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String datestr = MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      volleyChecked(datestr, "checked");//项目验收
    }
    if (requestCode == PROGRESS_REGIST) {
      backType = data.getStringExtra(EXTRA_TYPE);
      Intent i = new Intent();
      i.putExtra(EXTRA_TYPE, backType);
      getActivity().setResult(Activity.RESULT_OK, i);
      getActivity().finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyChecked(String datestr, String type) {

    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_CHECKED);
    HashMap<String, String> params = new HashMap<>();
    params.put("projectId", projectId);
    params.put("finishDate", datestr);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response(type));
  }

  private VolleyResponse response(String type) {
    backType = type;

    return new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        // 解析响应的字符串
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          Intent i = new Intent();
          i.putExtra(EXTRA_TYPE, backType);
          getActivity().setResult(Activity.RESULT_OK, i);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    };
  }

  public static DetailProjectProgressFragment newInstance(ProjectProgressSuper item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    DetailProjectProgressFragment fragment = new DetailProjectProgressFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static DetailProjectProgressFragment newInstance(ProjectProgressSuper item, String pmId,
      String projectId, String projectName) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    args.putSerializable(EXTRA_PM_ID, pmId);
    args.putSerializable(EXTRA_PROJECT_ID, projectId);
    args.putSerializable(EXTRA_PROJECT_NAME, projectName);
    DetailProjectProgressFragment fragment = new DetailProjectProgressFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
